package com.et.core.upgrade

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.et.install.upgrade.IUpgradeAidl

class Util {

    companion object {

        private var call: ((installAidl: IUpgradeAidl?) -> Unit)? = null

        private val serviceConnect = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                IUpgradeAidl.Stub.asInterface(service).also { al ->
                    call?.let {
                        it(al)
                    }
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {
            }
        }

        fun bindInstallService(ctx: Context, cl: (installAidl: IUpgradeAidl?) -> Unit) {
            call = cl
            Intent().also {
                it.component = ComponentName("com.et.install", "com.et.install.InstallService")
                ctx.bindService(it, serviceConnect, Context.BIND_AUTO_CREATE)
            }
        }

        fun unbindInstallService(ctx: Context) {
            ctx.unbindService(serviceConnect)
        }
    }
}